package com.ktjy;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class PubSubQueueProducer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //建立连接
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("127.0.0.1");
        factory.setPort(5672);
        factory.setUsername("guest");
        factory.setPassword("guest");
        factory.setVirtualHost("/T384");
        //创建连接对象
        Connection connection = factory.newConnection();
        //创建信道对象
        Channel channel = connection.createChannel();

        //定义交换机
        String exchangeName="pub_sub_exchange";
        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.FANOUT,true,false,false,null);
        //定义一个队列
        String smsQueue="sms_queue";
        channel.queueDeclare(smsQueue,true,false,false,null);
        String emailQueue="email_queue";
        channel.queueDeclare(emailQueue,true,false,false,null);
        //3.绑定队列和交换机
        channel.queueBind(smsQueue,exchangeName,"");
        channel.queueBind(emailQueue,exchangeName,"");

        //发信息
        String msg="hello world";
        channel.basicPublish(exchangeName,"",null,msg.getBytes());

        System.out.println("消息发送成功");

        //关闭信道和连接对象
        channel.close();
        connection.close();
    }
}
